from datetime import datetime, timezone

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework import status

# 当前应用模型
from .models import SegmentSchedule

# 跨应用模型
from ship_segments.models import ShipSegment
from .serializers import SegmentScheduleUpdateInputSerializer, SegmentScheduleCreateSerializer, \
    SegmentScheduleImportSerializer


class SegmentScheduleListView(APIView):
    def get(self, request, format=None):
        # 获取查询参数并转换为 datetime 对象
        ship_number = request.query_params.get('ship_number', '')
        mid_schedule_start_str = request.query_params.get('mid_schedule_start')
        mid_schedule_end_str = request.query_params.get('mid_schedule_end')

        # 将字符串转为 aware datetime，并使用 UTC 时区（与数据库保持一致）
        if mid_schedule_start_str:
            mid_schedule_start = datetime.strptime(mid_schedule_start_str, '%Y-%m-%dT%H:%M:%S.%fZ').replace(
                tzinfo=timezone.utc)
        else:
            mid_schedule_start = None

        if mid_schedule_end_str:
            mid_schedule_end = datetime.strptime(mid_schedule_end_str, '%Y-%m-%dT%H:%M:%S.%fZ').replace(
                tzinfo=timezone.utc)
        else:
            mid_schedule_end = None

        page = int(request.query_params.get('current', 1))
        page_size = int(request.query_params.get('pageSize', 8))

        # Step 1: 根据 ship_number 查找匹配的 ShipSegment 记录
        ship_segments = ShipSegment.objects.filter(ship_number__icontains=ship_number)

        # Step 2: 构造完整的结果数据列表
        schedule_data = []

        for ship_segment in ship_segments:
            segment_schedules = SegmentSchedule.objects.filter(
                ship_segments_id=ship_segment.ship_segments_id
            )

            if segment_schedules.exists():
                for schedule in segment_schedules:
                    item = {
                        'segment_schedule_id': schedule.segment_schedule_id,
                        'ship_segments_id': schedule.ship_segments_id,
                        'mid_schedule_start': schedule.mid_schedule_start,
                        'mid_schedule_end': schedule.mid_schedule_end,
                        'earliest_start': schedule.earliest_start,
                        'latest_start': schedule.latest_start,
                        'latest_end': schedule.latest_end,
                        'ship_number': ship_segment.ship_number,
                        'ship_type': ship_segment.ship_type,
                        'segment_number': ship_segment.segment_number
                    }
                    schedule_data.append(item)
            else:
                # 如果没有 SegmentSchedule 数据，则只展示 ShipSegment 字段
                item = {
                    'segment_schedule_id': None,
                    'ship_segments_id': ship_segment.ship_segments_id,
                    'mid_schedule_start': None,
                    'mid_schedule_end': None,
                    'earliest_start': None,
                    'latest_start': None,
                    'latest_end': None,
                    'ship_number': ship_segment.ship_number,
                    'ship_type': ship_segment.ship_type,
                    'segment_number': ship_segment.segment_number
                }
                schedule_data.append(item)

        # Step 3: 分页处理整个 schedule_data 列表
        paginator = Paginator(schedule_data, page_size)
        try:
            paginated_page = paginator.page(page)
        except PageNotAnInteger:
            paginated_page = paginator.page(1)
        except EmptyPage:
            paginated_page = paginator.page(paginator.num_pages)

        # Step 4: 遍历当前页的数据，手动筛选符合条件的时间范围
        filtered_list = []

        for item in paginated_page.object_list:
            mid_start = item['mid_schedule_start']
            mid_end = item['mid_schedule_end']

            # 如果都没有时间条件，则全部保留
            if not mid_schedule_start and not mid_schedule_end:
                filtered_list.append(item)
            else:
                match = True
                # 如果 item 的 mid_start 或 mid_end 为空，则跳过不显示
                if not mid_start or not mid_end:
                    continue
                if mid_schedule_start and mid_start:
                    # 确保 mid_start 是 aware 类型
                    match = match and (mid_start >= mid_schedule_start)
                if mid_schedule_end and mid_end:
                    match = match and (mid_end <= mid_schedule_end)
                if match:
                    filtered_list.append(item)

        return JsonResponse({
            "code": 200,
            "data": {
                "list": filtered_list,
                "total": paginator.count,
                "current": paginated_page.number,
                "pageSize": page_size
            }
        }, status=status.HTTP_200_OK)


class UpdateSegmentScheduleView(APIView):
    def put(self, request, *args, **kwargs):
        serializer = SegmentScheduleUpdateInputSerializer(data=request.data)

        if not serializer.is_valid():
            return JsonResponse({"code": 400, "message": "请求数据格式错误", "errors": serializer.errors},
                            status=status.HTTP_400_BAD_REQUEST)

        schedule_id = serializer.validated_data.get('segment_schedule_id')

        try:
            schedule = SegmentSchedule.objects.get(segment_schedule_id=schedule_id)
        except SegmentSchedule.DoesNotExist:
            return JsonResponse({"code": 404, "message": "未找到对应记录"},
                            status=status.HTTP_404_NOT_FOUND)

        # 执行更新
        serializer.update(schedule, serializer.validated_data)

        return JsonResponse({"code": 200, "message": "更新成功"}, status=status.HTTP_200_OK)



class CreateSegmentScheduleView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = SegmentScheduleCreateSerializer(data=request.data)

        if not serializer.is_valid():
            return JsonResponse(
                {"code": 400, "message": "请求数据格式错误", "errors": serializer.errors},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 创建新记录
        schedule = serializer.save()

        return JsonResponse(
            {
                "code": 200,
                "message": "新增成功",
                "data": serializer.data
            },
            status=status.HTTP_201_CREATED
        )
class BatchImportSegmentScheduleView(APIView):
    def post(self, request, *args, **kwargs):
        data_list = request.data.get('list', [])

        if not isinstance(data_list, list) or len(data_list) == 0:
            return JsonResponse({
                "code": 400,
                "message": "请传入有效的对象数组"
            }, status=status.HTTP_400_BAD_REQUEST)

        success_records = []
        error_records = []

        for idx, item in enumerate(data_list):
            serializer = SegmentScheduleImportSerializer(data=item)
            if serializer.is_valid():
                # 这里会执行 create() 方法中的 update_or_create()
                schedule = serializer.save()
                success_records.append(schedule)
            else:
                error_records.append({
                    "row_index": idx + 1,
                    "data": item,
                    "errors": serializer.errors
                })

        return JsonResponse({
            "code": 200,
            "message": f"成功导入 {len(success_records)} 条数据",
            "success_count": len(success_records),
            "failed_count": len(error_records),
            "errors": error_records
        }, status=status.HTTP_200_OK)
